package com.wlz.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.UUID;

/**
 * 生成二维码的工具类
 *
 * @author ：Administrator
 * @date ：2018/10/10/010 10:47
 */


public class QRCodeUtils {
    public static String produceQRCode(String path, String content) {
        int width = 300;
        int height = 300;
        String format = "png";
        String fileName = "";

        boolean flag = true;

        // 定义二维码参数
        HashMap hints = new HashMap();
        // 字符集
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 纠错级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 空白
        hints.put(EncodeHintType.MARGIN, 2);

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);
            fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
            Path file = new File(path + fileName).toPath();

            MatrixToImageWriter.writeToPath(bitMatrix, format, file);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }
}
